from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib.auth import authenticate, login
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from .forms import RegisterForm
from .data_utilized import get_top_data, is_scored, prediction_gcmc, score_user, is_new, take_rating, \
   prediction_cold_user, take_all, prediction_sim

# Create your views here.


def index(request):
    if request.method == 'POST':
        result = {'status': False,
                  'score': 0,
                  }
        user_id = request.POST.get('user_id')
        movie_id = request.POST.get('movie_id')
        rating = is_scored(user_id, movie_id) #判断是否已经评分过
        if rating:
            result['score'] = rating
        else:
            score = request.POST.get('score')
            score_user(user_id, movie_id, score) #保存评分
            result['status'] = True

        return JsonResponse(result)
    else:
        rec_movies = []
        id = request.session.get('_auth_user_id')
        if id:
            id = int(id)
            if is_new(id):
                rec_movies = prediction_sim(id)
            else:
                rec_movies = prediction_gcmc(id) #gcmc推荐
        movies, genres, genres_all = get_top_data() #获取热门数据
        context = {
            'movies': movies,
            'genres': genres,
            'genres_all': genres_all,
            'rec_movies': rec_movies,
        }
        return render(request, 'index.html', context=context)


def signup(request):
    if request.is_ajax():
        result = dict()
        result['key'] = CaptchaStore.generate_key()
        result['image_url'] = captcha_image_url(result['key'])
        return JsonResponse(result)
    if request.method == 'POST':

        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password1'])
            login(request, user) #注册成功后自动登录跳转
            return redirect(reverse('movie:index'))
    else:
        form = RegisterForm()

    return render(request, 'registration/signup.html', context={'form': form})


def user_scored(request, user_id):
    rating_list, rating_range = take_rating(user_id)
    context = {
        'rating_list': rating_list,
        'rating_range': rating_range,
    }
    return render(request, 'scored_user.html', context=context)


def movies_all(request):
    movies = take_all()
    paginator = Paginator(movies, 20)
    try:
        num = request.GET.get('movies_page')
        movies_page = paginator.page(num)
    except PageNotAnInteger:
        movies_page = paginator.page(1)
    except EmptyPage:
        movies_page = paginator.page(paginator.num_pages)
    context = {
        'movies': movies_page,
        'paginator': paginator,
    }
    return render(request, 'movies_all.html', context=context)